import {Component, OnInit} from '@angular/core';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {ActivatedRoute, Router} from '@angular/router';
import {Subscription} from 'rxjs';
import {CommodityService} from '../commodity.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import { validEvents } from '@tinymce/tinymce-angular/editor/Events';

@Component({
  selector: 'app-commodity-edit',
  templateUrl: './commodity-edit.component.html',
  styleUrls: ['./commodity-edit.component.scss']
})
export class CommodityEditComponent implements OnInit {
  form: any = {
    id: '',
    name: '',
    typeList: [],
    pictureId: '',
    sort: '',
    image: '',
    textureId: '', // 适用材质ID
  };
  categoryOptions: [] = [];
  imageModify = true;
  goodsListImg: any = {
    url: '',
    loading: false,
    fileList: []
  };
  saveBtnLoading = false;
  goodsDetailImg: any = {
    url: '',
    loading: false,
    fileList: []
  };
  goodsDetailCustomizationImg: any = {
    url: '',
    loading: false,
    fileList: []
  };

  // 适用材质
  textureOptions: any = [];

  constructor(
    private httpclient: HttpClient,
    private activatedRoute: ActivatedRoute,
    private commodityService: CommodityService,
    private nzMessageService: NzMessageService,
    private router: Router
  ) {
  }

  async ngOnInit() {
    await this.getTextureListData();

    let commodityDetail = this.activatedRoute.snapshot.queryParams.detail;
    if (commodityDetail) {
      commodityDetail = JSON.parse(this.activatedRoute.snapshot.queryParams.detail);
      // this.form.id = this.activatedRoute.snapshot.queryParams.detail || '';
      this.form.id = commodityDetail.id;
      this.form.name = commodityDetail.name;
      this.form.pictureId = commodityDetail.pictureId;
      this.form.sort = commodityDetail.sort;
      this.form.typeList = Array.from(commodityDetail.typeIds.split(',')).map((i: any) => i * 1);
      this.goodsListImg.url = commodityDetail.image;
      this.form.image = commodityDetail.image;
      this.imageModify = false;

      // 材质赋值
      this.form.textureId = commodityDetail.textureId;
      let textureIdArr = commodityDetail.textureId.split(',') || [];
      this.textureOptions.forEach((ele: any) => {
        if (commodityDetail.textureId == '0' || textureIdArr.includes(String(ele.value))) {
          ele.checked = true;
        } else {
          ele.checked = false;
        }
      });
      
    }
    console.log(this.form);
    this.queryCategory();
  }

  // 获取材质list
  async getTextureListData() {
    const res: any = await this.commodityService.getTextureListData();
    if (res.code == 0) {
      this.textureOptions = res.data.map((item: any) => {
        return {
          label: this.filterNum(res.data, item.textureName) ? item.textureName + '-' + item.textureColor : item.textureName,
          value: item.id,
          checked: false
        }
      })
    } else {
      this.nzMessageService.error(res.message);
    }
  }
  filterNum(array: any, textureName: string) {
    let tmp: any = [];
    if (array.length) {
      tmp = array.filter((item: any) => item.textureName == textureName);
    }
    return tmp.length > 1 ? true : false;
  }

  /*
  * 查询商品分类
  * */
  queryCategory() {
    this.commodityService.httpGet(this.commodityService.serviceUrl.category, null).then((res: any) => {
      this.categoryOptions = res.data;
      // this.categoryOptions = this.formatCateGory(res.data);
    }).catch(err => {
      console.log(err);
    });
  }

  customRequest = () => new Subscription();

  /*
  * 文件改变
  * */
  handleChange(info: { file: NzUploadFile }, obj: any): void {
    obj.fileList = [info.file.originFileObj];
    this.goodsListImg.url = '';
    this.imageModify = true;
    this.getBase64(info.file.originFileObj, img => {
      obj.url = img;
    });
  }

  /*
  * file转base64*/
  private getBase64(img: any, callback: (img: string) => void): void {
    const reader = new FileReader();
    // @ts-ignore
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  // 适用材质change
  textureChange(value: object[]) {
    let tempArr: any = [];
    if (value.length) {
      tempArr = value.filter((item: any) => {
        return item.checked;
      }).map((ele: any) => {
        return ele.value;
      })
    }

    this.form.textureId = tempArr.join(',');
    if (tempArr.length == this.textureOptions.length) {
      this.form.textureId = '0';
    }
  }

  show() {
    console.log(this.goodsListImg.fileList);
  }

  save() {
    if (!this.form.name) {
      this.nzMessageService.warning('请输入名称或编号');
      return;
    }
    if (!this.form.typeList.length) {
      this.nzMessageService.warning('请选择商品分类');
      return;
    }
    if (!this.form.pictureId) {
      this.nzMessageService.warning('请输入第三方id');
      return;
    }
    if (!this.form.name) {
      this.nzMessageService.warning('请输入序号');
      return;
    }
    if (!this.form.textureId) {
      this.nzMessageService.warning('请选择适用材质');
      return;
    }
    if (!this.goodsListImg.fileList.length && !this.goodsListImg.url) {
      this.nzMessageService.warning('请选择图片');
      return;
    }
    if (!this.imageModify) {
      this.form.image = this.goodsListImg.url;
      this.commodityService.httpPost(this.commodityService.serviceUrl.commodityAdd, this.form).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.router.navigate(['/customization/commodity']);
        } else {
          this.nzMessageService.error('操作失败');
        }
      }).finally(() => {
        this.saveBtnLoading = false;
      });
      return;
    }
    this.saveBtnLoading = true;
    const file = new FormData();
    file.append('file', this.goodsListImg.fileList[0]);
    file.append('name', (+new Date()).toString());
    console.log(this.goodsListImg.fileList[0]);
    this.commodityService.httpPost(this.commodityService.serviceUrl.fileUpload, file).then((res: any) => {
      if (res.code === 0) {
        this.form.image = res.data;
        this.commodityService.httpPost(this.commodityService.serviceUrl.commodityAdd, this.form).then((result: any) => {
          if (result.code === 0) {
            this.nzMessageService.success('操作成功');
            this.router.navigate(['/customization/commodity']);
          } else {
            this.nzMessageService.error('操作失败');
          }
        }).finally(() => {
          this.saveBtnLoading = false;
        });
      } else {
        this.saveBtnLoading = false;
      }
    });
  }

  // back
  bakc() {
    history.back();
  }
}
